﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NVelocity.Runtime;
using NVelocity.App;
using NVelocity.Context;

using NVelocity;
using System.IO;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Text;
using Commons.Collections;
using System.Collections.Generic;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
using Microsoft.VisualBasic;
using System.Net;


namespace lxwmvc
{
    public class pagebase : System.Web.UI.Page
    {
        private static VelocityEngine velocity = null;
        private IContext context = null;
        private bool _cancelview = false;
        private bool _cancellayout = false;
        private bool _exit = false;

        private string layoutname = "";
        private string _viewname = "";

        //是这部分的问题吗？
        string defaultcontroller = ConfigurationManager.AppSettings["defaultcontroller"];
        public Dictionary<string, object> cachepagevalue = new Dictionary<string, object>();
        /// <summary>
        /// 线程安全
        /// </summary>
        readonly static object[] syn = new object[0] { };
        //同步方法
        public static object m_monitorObject = new object();
        static Mutex m_mutex = new Mutex();//全局阻塞

        /// <summary>
        /// 不使用模板，其实在系统中，如果没有模板，系统也不会出现错误，他会自动不显示模板
        /// </summary>
        public void cancelview()
        {
            _cancelview = true;
        }

        /// <summary>
        /// 退出程序，后续不要再进行操作。
        /// </summary>
        public void exit()
        {
            _exit = true;
            throw new Exception("MMM:人工终止操作！");
        }

        /// <summary>
        /// 改变vm名称
        /// </summary>
        /// <param name="vm">不能带后缀 .htm</param>
        public void randerview(string vm)
        {
            //不能带后缀
            _viewname = vm;
        }

        /// <summary>
        /// 加载layout
        /// </summary>
        /// <param name="vm"></param>
        public void setlayout(string layout)
        {
            //重新设置layout
            layoutname = layout;
        }

        /// <summary>
        /// 不使用布局
        /// </summary>
        public void cancellayout()
        {
            _cancellayout = true;
        }

        string strcontroller = string.Empty;
        string straction = string.Empty;
        string strparse = string.Empty;


        /// <summary>
        /// 加入helper
        /// lxwmvc.Helpers.xxxhelper
        /// </summary>
        /// <param name="name"></param>
        public void addhelper(string name)
        {
            var t = applicationhelper.lxwmvcdll.Assembly.GetType(name);
            var _instance = t.Assembly.CreateInstance(name, false);
            this[name.Split('.')[name.Split('.').Length-1].ToLower()] = _instance;
        }


        /// <summary>
        /// 得到系统参数列表
        /// </summary>
        /// <returns></returns>
        public lxwdata getparams(string qianzhun = "")
        {
            lxwdata has = new lxwdata();
            foreach (string s in Request.Params.Keys)
            {
                if (!string.IsNullOrEmpty(s))//&& !s.Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    if (qianzhun == "")
                        has.Add(s.ToLower(), getonevalue(s));
                    else
                    {
                        if (s.ToLower().StartsWith(qianzhun.ToLower()))
                        {
                            string key = s.Substring(qianzhun.Length).ToLower();
                            if (key.StartsWith(".") || key.StartsWith("_") || key.StartsWith(">")) key = key.Substring(1);//如果是._> 直接去除
                            has.Add(key, getonevalue(s));
                        }
                    }
                }
            }

            //特殊处理一下checkbox 等于on的情况
            string keys = v_s("_lxw_column_checkbox_").ToLower();
            foreach (string s in keys.Split(','))
            {
                if (s.Length == 0) continue;
                if (has.ContainsKey(s))  //这里是写死了，如果允许，就是1，不允许就是0，只有两种状态，是否允许再数据库中配置一下？
                    has[s] = has[s].tostr() == "on" ? 1 : 0;
                else
                    has[s] = 0;
            }

            return has;
        }

        public supermodel getmodel(string tablename,string qianzhun = "")
        {
            supermodel has = supermodel.create(tablename);
            foreach (string s in Request.Params.Keys)
            {
                if (!string.IsNullOrEmpty(s))//&& !s.Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    if (qianzhun == "")
                        has.Add(s.ToLower(), getonevalue(s));
                    else
                    {
                        if (s.ToLower().StartsWith(qianzhun.ToLower()))
                        {
                            string key = s.Substring(qianzhun.Length).ToLower();
                            if (key.StartsWith(".") || key.StartsWith("_") || key.StartsWith(">")) key = key.Substring(1);//如果是._> 直接去除
                            has.Add(key, getonevalue(s));
                        }
                    }
                }
            }
            return has;
        }


        

        /// <summary>
        /// 可能再次使用
        /// </summary>
        Type currenttype = null;

        /// <summary>
        /// 外部执行内部方法 20121025
        /// </summary>
        /// <param name="fun"></param>
        /// <param name="arg"></param>
        /// <returns></returns>
        public string customfun(string fun,params object[] arg)
        {
            if (currenttype == null) return "";
            var currentmethod_ = getmethod(currenttype,fun);

            if (currentmethod_ == null) return "";
            if(arg == null || arg.Length == 0)
                currentmethod_.Invoke(null, new object[] { this});
            else
                currentmethod_.Invoke(null, new object[] { this, arg });

            return "";
        }
        /// <summary>
        /// 页面加载核心函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Page_Load(object sender, EventArgs e)
        {
            //__PageBase();
            try
            {
                //Request.ContentEncoding = Encoding.UTF8;
                
                strcontroller = v_s("_controller_");
                straction = v_s("_action_");
                //有些地方就是无法获取的数据
                strparse = Request.QueryString["_parse_"];

                //if (DateTime.Now > new DateTime(2013, 12, 1))
                //{
                //    throw new Exception("软件已经超出试用期，请购买正版.");
                //}

                if (!string.IsNullOrEmpty(straction))
                {
                    context = new VelocityContext();
                }
                //string ss = Request.QueryString.ToString();
                //默认controller
                if (strcontroller == "_defaultcontroller_")
                {
                    strcontroller = defaultcontroller;

                    if (applicationhelper.citypage != null && applicationhelper.citypage.ContainsKey(straction.ToLower()))
                    {
                        cachepagevalue["jiancheng"] = applicationhelper.citypage[straction.ToLower()];
                        strcontroller = "default";
                        straction = "city";
                    }

                    //查找单独系统页面 20120727,可能存在问题，20121024
                    if (applicationhelper.syspages != null && applicationhelper.syspages.ContainsKey(straction.ToLower()))
                    {
                        //this.cancellayout();
                        //this.redirect("/sys/syspages?id=" + applicationhelper.syspages[straction.ToLower()]);
                        //this.Server.Transfer("/sys/syspages?id=" + applicationhelper.syspages[straction.ToLower()]);
                        cachepagevalue["id"] = applicationhelper.syspages[straction.ToLower()];
                        strcontroller = "sys";
                        straction = "syspages";
                    }
                    //20121025,系统页面
                }

                if (!string.IsNullOrEmpty(straction))
                {
                    context = new VelocityContext();
                    _viewname = straction;

                    MethodInfo currentmethod = null;
                    //普通模式
                    if (!string.IsNullOrEmpty(strparse) && strparse.Equals("true", StringComparison.OrdinalIgnoreCase))
                    {
                        //currenttype = typeof(_parse_controller);
                        currenttype = applicationhelper.lxwmvcdll.Assembly.GetType("lxwmvc._parse_controller", true, true);
                        currentmethod = currenttype.GetMethod("parse");
                    }
                    else
                    {
                        //这里可能会存在问题
                        currenttype = applicationhelper.lxwmvcdll.Assembly.GetType("lxwmvc." + strcontroller + "controller", true, true);
                        currentmethod = getmethod(currenttype, straction, ref straction);


                    }
                    //得到真实的
                    _viewname = straction;
                    //真实的action名称
                    if (currentmethod != null)
                        straction = currentmethod.Name.ToLower();

                    //List<Attribute> controllerattribute = new List<Attribute>();
                    List<Attribute> actionattribute = new List<Attribute>();
                    if (currentmethod != null)
                    {
                        object[] attrs = currentmethod.GetCustomAttributes(false);
                        if (attrs != null && attrs.Length > 0)
                        {
                            foreach (var o in attrs)
                            {
                                actionattribute.Add(o as Attribute);
                            }
                        }
                    }


                    if (currenttype != null)
                    {
                        object[] attrs = currenttype.GetCustomAttributes(false);
                        if (attrs != null && attrs.Length > 0)
                        {
                            foreach (var o in attrs)
                            {
                                actionattribute.Add(o as Attribute);
                            }
                        }
                    }

                    /*
                    //判断权限和菜单
                    var quanxian1 = actionattribute.Find(o => o.GetType() == typeof(menuAttribute));
                    var quanxian2 = actionattribute.Find(o => o.GetType() == typeof(powerAttribute));
                    var quanxian3 = actionattribute.FindAll(o => o.GetType() == typeof(yilaiAttribute));

                    quanxian1 = null;
                    quanxian2 = null;
                    quanxian3 = null;

                    //如果不设置，代表不受限制
                    if (quanxian1 != null)
                    {
                        if (!in_string(globalhelper.powerstring, "m@" + strcontroller + "@" + straction + ""))
                            throw new Exception("AAA1:没有权限!");
                    }
                    if (quanxian2 != null)
                    {
                        if (!in_string(globalhelper.powerstring, "p@" + strcontroller + "@" + straction + ""))
                            throw new Exception("AAA2:没有权限!");
                    }
                    if (quanxian3 != null)
                    {
                        foreach (var qx in quanxian3)
                        {
                            string name = (qx as yilaiAttribute).powername.ToLower();
                            if (name.StartsWith("p@"))
                            {
                                if (!applicationhelper.hasPower.ContainsKey(name))
                                    throw new Exception("AAA310:依赖权限“" + name + "”没有找到!");

                                powerAttribute p = applicationhelper.hasPower[name];
                                if (p != null && !in_string(globalhelper.powerstring, p.powername))
                                    throw new Exception("AAA31:没有权限!");
                            }
                            if (name.StartsWith("m@"))
                            {
                                if (!applicationhelper.hasMenu.ContainsKey(name))
                                    throw new Exception("AAA320:依赖菜单“" + name + "”没有找到!");

                                menuAttribute p = applicationhelper.hasMenu[name];
                                if (p != null && !in_string(globalhelper.powerstring, p.menuname))
                                    throw new Exception("AAA32:没有权限!");
                            }

                        }
                    }

                    {
                        //获取变态权限
                        string name = strcontroller + "/" + straction;
                        if (strcontroller.ToLower() == "table") name = table + "/" + straction;
                        if (applicationhelper.hasViews.ContainsKey(name.ToUpper()))
                        {
                            var l = applicationhelper.hasViews[name.ToUpper()];
                            if (l[0] == "menu")
                            {
                                if (!in_string(globalhelper.powerstring, "m@" + l[1] + "@" + l[2]))
                                    throw new Exception("AAA1_1:没有权限!");
                            }
                            if (l[0] == "power")
                            {
                                if (!in_string(globalhelper.powerstring, "p@" + l[1] + "@" + l[2]))
                                    throw new Exception("AAA2_1:没有权限!");
                            }
                            if (l[0] == "yilai")
                            {
                                foreach (var s in l[3].Split(','))
                                {
                                    //可能存在多个依赖
                                    if (!in_string(globalhelper.powerstring, s))
                                        throw new Exception("AAA3_1:没有权限!");
                                }
                            }
                        }
                    }
                    */

                    var trans = actionattribute.Find(o => o.GetType() == typeof(transAttribute));
                    //查找事务
                    if (trans != null)
                    {
                        //存在事务
                        Session[sqlhelper.has_transaction] = trans;
                    }

                    var _init = getmethod(currenttype, "_init");
                    //这句话非常重要
                    if (_init != null) _init.Invoke(null, new object[] { this });


                    if (!string.IsNullOrEmpty(strparse) && strparse.Equals("true", StringComparison.OrdinalIgnoreCase))
                    {
                        if (currentmethod != null)
                            currentmethod.Invoke(null, new object[] { this, strcontroller, straction });
                        else
                            writelog("在_parse_controller中没有找到方法:{0}", straction);
                    }
                    else
                    {
                        if (currentmethod != null)
                        {
                            var lc = actionattribute.FindAll(o => o.GetType() == typeof(tongbuAttribute));
                            if (lc == null || lc.Count == 0)
                                currentmethod.Invoke(null, new object[] { this });
                            else
                            {
                                try {
                                    //加方法锁
                                    m_mutex.WaitOne();
                                    currentmethod.Invoke(null, new object[] { this });
                                }
                                finally
                                {
                                    m_mutex.ReleaseMutex();
                                }

                            }
                        }
                        else
                        {
                            
                            {
                                //Response.StatusCode = (int)HttpStatusCode.NotFound;
                                //strcontroller = "customerrors";
                                //_viewname = "404";

                                //Response.WriteFile("/views/customerrors/404.htm");

                                writelog("在{1}controller中没有找到方法:{0}", straction, strcontroller);
                            }
                        }
                    }

                    //如果不设置，是直接加载layout的
                    if (!_cancellayout)
                    {
                        //找方法上的
                        var layout = actionattribute.Find(o => o.GetType() == typeof(layoutAttribute));
                        if (layout != null)
                        {
                            layoutname = (layout as layoutAttribute).layoutname;
                        }
                    }

                    //输出helper信息
                    var helpers = actionattribute.FindAll(o => o.GetType() == typeof(helperAttribute));
                    foreach (helperAttribute o in helpers)
                    {
                        if (this.context.ContainsKey(o.helpertype.Name.ToLower())) continue;
                        this[o.helpertype.Name.ToLower()] = o.instance;
                    }


                    //把日期输出去
                    this["now"] = DateTime.Now;
                    this["this"] = this;

                    //把request输出出去
                    foreach (string s in Request.QueryString.Keys)
                    {
                        //如果已经存在，就不要输出出去了。
                        if (!context.ContainsKey(s))
                        {
                            this[s] = Server.HtmlDecode(Request.QueryString[s]);
                        }
                    }

                    //把全局helper压缩出去
                    this["globalhelper"] = new globalhelper();
                    //this["formhelper"] = new formhelper();
                    this["funhelper"] = new funhelper();
                    this["jiandansql"] = new queryhelper();
                    this["stringhelper"] = new stringhelper();
                    this["request"] = Request;

                    try
                    {
                        this["config_qiyemingcheng"] = System.Configuration.ConfigurationManager.AppSettings["config_qiyemingcheng"].ToString();
                    }
                    catch { }

                    //随机数
                    this["random"] = "__i=" + Guid.NewGuid().ToString();
                    //把这个替换成$
                    this["_JQ_"] = "$";
                    //如果没有设置，系统默认设置这个值
                    if (!context.ContainsKey("formurl"))
                        this["formurl"] = requesthelper.formurl();

                    //QueryString
                    //this["querystring"] = Request.QueryString.ToString();

                    //显示模板
                    //如果是单表操作

                    if (_viewname.IndexOf("\\") != -1 || _viewname.IndexOf("/") != -1)
                    {
                        //不能带后缀
                        display(_viewname);
                    }
                    else
                    {
                        if (table.Length > 0 && strcontroller == "table")
                            display(table + "\\" + _viewname + ".htm");
                        else
                            display(strcontroller + "\\" + _viewname + ".htm");
                    }
                }
                else
                {
                    pageaction();
                }

                //统一提交事务
                sqlhelper.transactioncommit();
            }
            //[System.Threading.ThreadAbortException] = {由于代码已经过优化或者本机框架位于调用堆栈之上，无法计算表达式的值。}
            catch (ThreadAbortException)
            {
                //Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                Console.Write("ThreadAbortException");
            }
            catch (Exception err)
            {
                //错误信息
                //Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                sqlhelper.transactionrollback();

                if (_exit == false)
                {
                    Response.StatusCode = 404;
                    string msg = writelog(err);
#if DEBUG
                    //jshelper.echo("alert('发生异常:" + encodejscript(msg).Replace("'", "\'").Replace("\r", "").Replace("\n", "") + "');");

                    string kmsg = "";
                    if (err.InnerException != null)
                        kmsg = err.InnerException.Message;
                    else
                        kmsg = err.Message;

                    kmsg = encodejscript(kmsg).Replace("'", "\'").Replace("\r", "").Replace("\n", "");

                    msg = ("alert('错误提示:" + kmsg + "');try{setfirst();}catch(e){}");

                    if (v_s("_ajax_submit_") == "1")
                    {//直接输出字符串,隐藏提交。
                        write(msg);
                    }
                    else
                    {
                        jshelper.echo(msg);
                    }
#else

                    string kmsg = "";
                    if (err.InnerException != null)
                        kmsg = err.InnerException.Message;
                    else
                        kmsg = err.Message;

                    kmsg = encodejscript(kmsg).Replace("'", "\'").Replace("\r", "").Replace("\n", "");

                    //不要跳出sql语句 lxw
                    msg = ("alert('错误提示:请查看日志');try{setfirst();}catch(e){};try{parent.setjiage(-1);}catch(e){}");

                    //if (v_s("_ajax_submit_") == "1")
                    //{//直接输出字符串,隐藏提交。
                    //    write(msg);
                    //}
                    //else
                    //{
                    //    jshelper.echo(msg);
                    //}

                    jshelper.echo(msg);
#endif
                }


            }
            finally
            {
                //释放session
                sqlhelper.dbconnectclose();
                Session.Remove(sqlhelper.has_transaction);
                Session.Remove(sqlhelper.session_transaction);
                Session.Remove(sqlhelper.session_connect);
            }
        }

        //临时变量
        string[] _1 = { null, null, null, null };
        /// <summary>
        /// 用于单表操作的主键
        /// </summary>
        public string pk
        {
            get { return _1[0]??v_s("_pk_"); }
            set { _1[0] = value; }
        }        

        /// <summary>
        /// 用于单表操作的表
        /// </summary>
        public string table
        {
            //get { return v_s(""); }
            get { return _1[1]??v_s("_table_"); }
            set { _1[1] = value; }
        }

        /// <summary>
        /// 级联
        /// </summary>
        public string[] jilians
        {
            //get { return v_s("_ji_lian_").Split('_'); }
            get { return (_1[2]??v_s("_ji_lian_")).Split('_'); }
            set { _1[2] = string.Join("_",value); }
        }

        /// <summary>
        /// 是否存在级联
        /// </summary>
        public bool hasjilian
        {
            get { return jilians.Length == 3; }
        }

        /// <summary>
        /// 设置级联
        /// </summary>
        /// <param name="zibiao"></param>
        /// <param name="zibiaoid"></param>
        /// <param name="guanlianjian"></param>
        /// <returns></returns>
        public string setjilian(object zibiao, object zibiaoid, object guanlianjian)
        {
            return string.Format("_ji_lian_={0}_{1}_{2}", zibiao.tostr(), zibiaoid.tostr(), guanlianjian.tostr());
        }

        /// <summary>
        /// 自动装载数据
        /// </summary>
        public void autoloaddata(DataSet ds, string key = "loadformdatas",Dictionary<string,string> di = null)
        {
            if (key == "") key = "loadformdatas";
            string keyvalues = "";
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count == 1)
            {
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)//输出一段代码
                {
                    //if (ds.Tables[0].Columns[i].ColumnName.ToLower() == "neirong") continue;
                    //可能还是存在问题？？？ 
                    keyvalues += ds.Tables[0].Columns[i].ColumnName.ToLower() + ":\"" +
                        Strings.Replace(encodejscript(ds.Tables[0].Rows[0][i].tostr()),
                        "script","p",1,-1, CompareMethod.Text) + "\",\n";
                    continue;
                }
                this[key] = ds.Tables[0].Rows[0];
                //原来的key太不好记了。
                this["body"] = ds.Tables[0].Rows[0];
            }
            if (di != null)
            {
                foreach (string k in di.Keys)
                {
                    keyvalues += k.ToLower() + ":\"" +
                       Strings.Replace(encodejscript(di[k].tostr()),
                       "script", "p", 1, -1, CompareMethod.Text) + "\",\n";
                    this[k] = di[k].tostr();
                }
                
            }
            keyvalues += "__end__:\"lxw\"";            

            //把数据压出去
            this["loadformdata"] = "<script>\r\nvar DATA=\r\n{\r\n" + keyvalues + "\r\n}\r\naddonload(loadform);\r\n</script>";
           
        }

        /// <summary>
        /// 检查request中key是否为空，如果为空 抛出异常
        /// </summary>
        /// <param name="key"></param>
        /// <param name="msg"></param>
        public void check_empty(string key, string msg)
        {
            if (string.IsNullOrEmpty(v_s(key))) throw new Exception(msg);
        }
        /// <summary>
        /// 判断表达式是否正确，如果为真 抛出异常
        /// </summary>
        /// <param name="exp"></param>
        /// <param name="msg"></param>
        public void iftrueerror(bool exp, string msg)
        {
            if (exp) throw new Exception(msg);
        }

        public string encodejscript(string strJsMsg)
        {
            Regex re = new Regex("\\\\|\\\"|\\\r|\\\n|\\\'|\\<|\\>|\\&", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
            return re.Replace(strJsMsg, new MatchEvaluator(encodejscript));
        }

        string encodejscript(Match m)
        {
            int code = (int)m.Value[0];
            string chars = "0123456789ABCDEF";
            int a1 = code & 0xF;
            int a2 = (code & 0xF0) / 0x10;
            // int   a3=(code&0xF00)/0x100;  
            // int   a4=(code&0xF000)/0x1000;  
            // return   "\\u"+chars[a4]+chars[a3]+chars[a2]+chars[a1];  
            return "\\x" + chars[a2] + chars[a1];
        }



        public string writelog(Exception lastException)
        {
            StringBuilder sb = new StringBuilder();
            writeerrorlog(sb, lastException);

            return writelog(sb.ToString());
        }

        /// <summary>
        /// 执行一条语句得到字段的内容
        /// </summary>
        /// <param name="table"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="idvalue"></param>
        /// <returns></returns>
        public string getname(object table, object name, object id, object idvalue)
        {
            //修正，不一定正确，好像还存在隐患
            string sql = "select top 1 {0} from {1} where cast({2} as nvarchar(50))='{3}'";
            return sqlhelper.@object(string.Format(sql, name, table, id, idvalue)).tostr();
        }

        /// <summary>
        /// 为了解决再循环中多次查找数据的的问题
        /// </summary>
        /// <param name="table"></param>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <param name="drs"></param>
        /// <param name="guanlianid"></param>
        public void innerstr(object table, object name, object id, DataRowCollection drs, string guanlianid = "")
        {
            _inner(table, name, id, drs, guanlianid, "'");
        }
        public void innerint(object table, object name, object id, DataRowCollection drs, string guanlianid = "")
        {
            _inner(table, name, id, drs, guanlianid, "");
        }
        private void _inner(object table, object name, object id, DataRowCollection drs,string guanlianid="",string k="'" )
        {
            string key = id.tostr();
            if (!string.IsNullOrEmpty(guanlianid)) key = guanlianid.tostr();

            string where = " in (" + k + "-10000" + k + "";
            foreach (DataRow dr in drs)
            {
                where += "," + k + "" + dr[key].tostr().Replace("'", "''") + "" + k + "";
            }
            where += ")";

            string sql = "select {0} as 'newvalue',{1} as 'newkey' from {2} where {1} {3}";
            //暂时存储起来
            this[table + "_" + name] = sqlhelper.rows(string.Format(sql, name, id, table, where));
        }
        //获取值
        public string innervalue(object table, object name, object key)
        {
            try {
                DataRowCollection drs = (DataRowCollection)this[table + "_" + name];
                foreach (DataRow dr in drs)
                    if (dr["newkey"].tostr() == key.tostr())
                        return dr["newvalue"].tostr();
            }
            catch { }
            return "";
        }
        /// <summary>
        /// 得到字典
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string getzidian(object id)
        {
            if (string.IsNullOrEmpty(id.tostr())) return "";
            try
            {
                string sql = "select top 1 mingcheng from zidian where zidianid=" + id.toint32(-1) + " ";
                return sqlhelper.@object(sql).tostr();
            }
            catch { } return id.tostr();
        }

        /// <summary>
        /// 通过字典产生options
        /// </summary>
        /// <param name="bianma"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public string getoptions(object bianma, string value="")
        {
            string sql = "select * from zidian where zidianleibieid in (select zidianleibieid from zidianleibie where  bianma='" + bianma + "')";
            StringBuilder sb = new StringBuilder();
            DataTable dt = sqlhelper.dataset(sql).Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append("<option value=" + dr["zidianid"].tostr() + " " + (dr["zidianid"].tostr().ToLower() == value.tostr().ToLower() ? "selected" : "") + ">" + dr["mingcheng"].tostr() + "</option>\r\n");
            }
            return sb.tostr();
        }

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="smsg"></param>
        /// <param name="arg"></param>
        /// <returns></returns>
        string writelog(string smsg, params object[] arg)
        {
            if (arg != null && arg.Length > 0)
                smsg = string.Format(smsg, arg);

            if (smsg != "")
            {
                lock (syn)
                {
                    string filename = DateTime.Now.ToString("yyyyMM") + ".log";
                    string folderpath = Server.MapPath("/log");
                    if (!Directory.Exists(folderpath)) Directory.CreateDirectory(folderpath);
                    FileInfo fi = new FileInfo(Path.Combine(folderpath, filename));
                    StreamWriter sw = null;
                    if (!fi.Exists)
                        sw = fi.CreateText();
                    else
                        sw = fi.AppendText();

                    sw.WriteLine(Request.Url.ToString());
                    sw.WriteLine(DateTime.Now + "\n" + smsg + "\n");
                    sw.WriteLine("================================================================>");
                    sw.Flush();
                    sw.Close();
                }
            }

            return smsg;
        }


        /// <summary>
        /// 构造错误日志
        /// </summary>
        /// <param name="sb">存储错误日志</param>
        /// <param name="exception">错误信息</param>
        private void writeerrorlog(StringBuilder sb, Exception exception)
        {
            sb.Append("错误类型:" + exception.GetType().Name + "\r\n");
            sb.Append("错误信息:" + exception.Message + "\r\n");

            if (!string.IsNullOrEmpty(exception.StackTrace))
                sb.Append("StackTrace:\r\n" + exception.StackTrace + "\r\n");

            if (exception.InnerException != null)
            {
                sb.Append("InnerException:\r\n");
                writeerrorlog(sb, exception.InnerException);
            }
        }

        /// <summary>
        /// 得到方法体,也可以通过别名找
        /// </summary>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        MethodInfo getmethod(Type type, string name, ref string truename)
        {
            MethodInfo[] ms = type.GetMethods(BindingFlags.Public | BindingFlags.Static);
            foreach (MethodInfo m in ms)
            {
                string bieming = m.Name;
                {
                    object[] attrs = m.GetCustomAttributes(typeof(biemingAttribute), false);
                    if (attrs != null && attrs.Length > 0)
                    {
                        bieming = (attrs[0] as biemingAttribute).bieming;
                    }
                }

                //忽略大小写
                if (bieming.Trim().Equals(name.Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    //别名作为新的vm文件
                    //_viewname = bieming.Trim();
                    truename = bieming.Trim();
                    return m;
                }
            }

            return null;
        }
        MethodInfo getmethod(Type type, string name)
        {
            return getmethod(type, name, ref name);
        }

        /// <summary>
        /// 如果需要扩充其他页面
        /// </summary>
        protected virtual void pageaction()
        {

        }

        /// <summary>
        /// 没有值，或者转换失败，都用0代替，也可以自己设置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public int v_i(string key, int def = 0)
        {
            string value = getonevalue(key);
            try
            {
                if (value == null)
                {
                    //writelog("无法取到Request.Params[\"{0}\"]的数据!", key);
                    return def;
                }

                return value.toint32(def);
            }
            catch
            {
                writelog("[{0}]转换整数失败!", value);

                return def;
            }
        }

        public string formurl
        {
            get
            {
                string url = v_s("formurl");
                return url;

                //string pre = "";
                //string k = "";
                //if(url.IndexOf('?') == 0) 
                //{
                //    pre=url;
                //}
                //else
                //{
                //    k = url.Substring(url.IndexOf('?')+1);
                //    pre = url.Substring(0,url.IndexOf('?'));
                //}
                
                //Dictionary<string, string> di = new Dictionary<string, string>();
                //if (k.Trim() != "")
                //{
                //    string[] ks = k.Split(new char[]{'=','&'});
                //    for (int i = 0; i < ks.Length / 2; i++)
                //        di[ks[i * 2]] = ks[i * 2 + 1];
                //}

                //di["_lxw_column_searchkeys_"] = v_s("_lxw_column_searchkeys_");
                //di["_lxw_column_keyvalue_"] = v_s("_lxw_column_keyvalue_");
                //foreach (string s in di["_lxw_column_searchkeys_"].Split(','))
                //{
                //    if (string.IsNullOrEmpty(s)) continue;
                //    di[s] = v_s(s);
                //}

                

                //StringBuilder sb = new StringBuilder();
                //sb.Append("1=1");
                //foreach (var o in di)
                //{
                //    sb.Append("&");
                //    sb.Append(o.Key + "=" + o.Value);
                //}


                ////返回数据
                //return pre + "?" + sb.ToString();
            }
        }

        public string v_s(string key)
        {
            string value = getonevalue(key);
            sqlvalidator.checkstring(value);//防止sql注入
            if (value == null)
            {
                //writelog("无法取到Request.Params[\"{0}\"]的数据!", key);
                return "";
            }

            return value;
        }

        public string v_ss(string key)
        {
            string value = getonevalue(key);
            if (value == null)
            {
                //writelog("无法取到Request.Params[\"{0}\"]的数据!", key);
                return "";
            }

            return value.Replace("'", "''").Split(';')[0];
        }

        public decimal v_dec(string key)
        {
            string value = getonevalue(key);
            try
            {
                if (value == null)
                {
                    //writelog("无法取到Request.Params[\"{0}\"]的数据!", key);
                    return 0m;
                }

                return Convert.ToDecimal(value);
            }
            catch
            {
                writelog("[{0}]转换decimal失败!", value);

                return 0m;
            }
        }

        public DateTime v_date(string key)
        {
            string value = getonevalue(key);
            try
            {
                if (value == null)
                {
                    //writelog("无法取到Request.Params[\"{0}\"]的数据!", key);
                    return new DateTime(1900, 1, 1);
                }

                return Convert.ToDateTime(value);
            }
            catch
            {
                writelog("[{0}]转换日期失败!", value);

                return new DateTime(1900, 1, 1);
            }
        }


        //系统初始化
        static pagebase()
        {
            velocity = new VelocityEngine();

            //ExtendedProperties props = new ExtendedProperties();
            //props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir));
            //props.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312");
            //props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312");
            //velocity.Init(props);


            //使用设置初始化VelocityEngine

            ExtendedProperties props = new ExtendedProperties(HttpContext.Current.Server.MapPath("/nvelocity.properties"));
            props[RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH] = HttpContext.Current.Server.MapPath(props[RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH].ToString());
            velocity.Init(props);
        }




        const String pagesearch = "pagesearch";
        /// <summary>
        /// 在action="?$!{pagesort}"使用
        /// </summary>
        const String pagesort = "pagesort";

        private string pagesearchdata = String.Empty;
        private string pagesortdata = String.Empty;



        /// <summary>
        /// 功能:分页需要传递到VM页面的参数
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <param name="blnencrypt">参数是否需要加密，如果加密的话，接收的时候就必须解密</param>
        public void dopager(bool blnencrypt)
        {
            if (pagesearchdata != null && pagesearchdata.StartsWith("&"))
                pagesearchdata = pagesearchdata.Substring(1);
            else
                pagesearchdata = String.Empty;
            //如果没有数据，传递一个空的，再前面至少不会出现错误。
            if (string.IsNullOrEmpty(pagesearchdata) || pagesearchdata.Trim().Length == 0) pagesearchdata = "_=_";

            if (blnencrypt)
            {
                this[pagesearch] = cryptohelper.encode(pagesearchdata);
                this[pagesort] = cryptohelper.encode(pagesortdata);
            }
            else
            {
                this[pagesearch] = pagesearchdata;
                this[pagesort] = pagesortdata;
            }
        }

        /// <summary>
        /// 功能:参考DoPager(false),不加密参数
        /// [09.4.12 lxw]<para />
        /// </summary>
        public void dopager()
        {
            dopager(false);
        }


        /// <summary>
        /// 解密ID类
        /// </summary>
        //Regex MyRegex = new Regex(
        //    "\\(\\-([^\\-\\(\\)]+)\\-\\)",
        //  RegexOptions.IgnoreCase
        //  | RegexOptions.IgnorePatternWhitespace
        //  );


        /// <summary>
        /// 取request中对应键的值<para />
        /// blnSearch为True的是作为分页需要的字符串，但是如果blnHtml为true，blnSearch设置不起作用;<para />
        /// 功能:blnHtml值里面如果存在HTML格式<para />
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <param name="strKey">request.params[strKey]中的键</param>
        /// <param name="blnHtml">true:值里面有html代码，不要进行编码 true为允许html编码存在</param>
        /// <param name="blnSearch">true:是否把值传递到分页中</param>
        /// <returns>返回对应request中key的value</returns>
        public String paramsvalue(String strKey, bool blnSearch = false, bool blnHtml = false)
        {
            string strvalue = getonevalue(strKey);// Request.Params[strKey];
            if (strvalue == null) return "";
            //else strValue = TreeBuilder.DecodeParamValue(strValue);
            //SqlValidator.CheckString(strValue);

            if (strvalue != null && blnSearch)
            {
                this[strKey] = strvalue;
                insertpagevalue(strKey, strvalue);
            }

            if (blnHtml)
                return strvalue == null ? "" : strvalue.ToString();

            return stringhelper.htmlencode(strvalue.ToString().Replace("'", "''"));
        }

        /// <summary>
        /// 功能:把对应的键值插入到分页参数中
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <param name="strKey">request.params[strKey]中的键</param>
        /// <param name="objValue">request.params[strKey]结果</param>
        public void insertpagevalue(String strKey, object objValue)
        {
            string strTemp = "&" + strKey + "=";
            objValue = objValue == null ? "" : objValue;
            if (stringhelper.instr(pagesearchdata, strTemp) == -1)
            {
                pagesearchdata += "&" + strKey + "=" + HttpContext.Current.Server.UrlEncode(objValue.ToString().Trim());
                //如果是这三个值，一定要进行组合
                string strKeys = "ot/ps/cn";
                if (in_string(strKeys, strKey.ToLower(), '/'))
                {
                    pagesortdata += "&" + strKey + "=" + HttpContext.Current.Server.UrlEncode(objValue.ToString().Trim());
                }
            }
        }

        /// <summary>
        /// [此方法不再使用]同等php方法的echo，相当于response.write...其中obj中的字符串会被参数格式化
        /// </summary>
        /// <param name="objvalue">需要response的字符串</param>
        /// <param name="objargs">格式化里面的占位符,可以省略</param>
        public void echo(object objvalue, params object[] objargs)
        {
            string strvalue = (objvalue).tostr();

            if (objargs != null && objargs.Length > 0)
            {
                strvalue = string.Format(strvalue, objargs);
            }

            Response.Write(strvalue);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于StringHelper.HTMLEncode
        /// </summary>
        /// <param name="objvalue">需要被编码的字符串</param>
        /// <returns>返回编码后的字符串</returns>
        public string htmlspecialchars(object objvalue)
        {
            return objvalue.tostr()
                .Replace("&", "&amp;")
                .Replace("<", "&lt;")
                .Replace(">", "&gt;");
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于StringHelper.Replace
        /// </summary>
        /// <param name="strfind">被查找的字符串</param>
        /// <param name="strrepalce">替换成的字符串</param>
        /// <param name="objsource">需要被替换的字符串</param>
        /// <returns>返回替换后的字符串</returns>
        public string str_replace(string strfind, string strrepalce, object objsource)
        {
            if (strfind == "")
            {
                return (objsource).tostr();
            }

            return (objsource).tostr().Replace(strfind, strrepalce);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于StringHelper.InStr,不取法大小写查找
        /// </summary>
        /// <param name="strsource">参考StringHelper.InStr</param>
        /// <param name="strfind">参考StringHelper.InStr</param>
        /// <returns>true:找到字符串,false找不到字符串</returns>
        public bool strstr(string strsource, string strfind)
        {
            return stringhelper.instr(strsource, strfind) != -1;
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于IndexOf
        /// </summary>
        /// <param name="strsource">查找源字符串</param>
        /// <param name="strfind">查找字符串</param>
        /// <param name="intpos">查找的起始位置</param>
        /// <returns>返回查找后的位置</returns>
        public int strpos(string strsource, string strfind, int intpos)
        {
            return strsource.IndexOf(strfind, intpos);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于Substring
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="intstartpos">截取的起始位置</param>
        /// <param name="intlength">截取字符串的长度</param>
        /// <returns>返回截取后的字符串</returns>
        public string substr(string strSource, int intstartpos, int intlength)
        {
            return strSource.Substring(intstartpos, intlength);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于Substring
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="intstartpos">截取的起始位置</param>
        /// <returns>返回截取后的字符串</returns>
        public string substr(string strSource, int intstartpos)
        {
            return strSource.Substring(intstartpos);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,相当于Length
        /// </summary>
        /// <param name="strsource">源字符串</param>
        /// <returns>返回字符串的长度</returns>
        public int strlen(string strsource)
        {
            return strsource.Length;
        }

        /// <summary>
        /// 为了解决params object[] keys 传递一个字符串的情况
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string removekey(string key)
        {
            return removekey(new object[] { key });
        }
        /// <summary>
        /// 移除对应Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string removekey(params object[] keys)
        {
            string str = this[pagesearch].tostr();
            if (keys == null) return str;

            string[] new_key = new string[keys.Length + 2];
            keys.CopyTo(new_key, 0);
            new_key[keys.Length] = "_lxw_column_searchkeys_";
            new_key[keys.Length] = "_lxw_column_keyvalue_";
            //new_keys.Add("_lxw_column_searchkeys_");
            //new_keys.Add("_lxw_column_keyvalue_");

            //string searchkeys = paramsvalue("_lxw_column_searchkeys_", true);
            //string exp = paramsvalue("_lxw_column_keyvalue_", true);

            Dictionary<string, string> lst = new Dictionary<string, string>();
            foreach (string s in str.Split('&'))
            {
                if (string.IsNullOrEmpty(s)) continue;
                lst[s.Split('=')[0].Trim() + "="] = s;
            }

            foreach (object k in new_key)
            {
                if (lst.ContainsKey(k.tostr().Trim() + "="))
                {
                    //移出
                    lst.Remove(k.tostr().Trim() + "=");
                }
            }

            



            if (lst.Count == 0) return "_=_";
            return string.Join("&", lst.Values);
        }

        //&_lxw_column_searchkeys_=leixing&_lxw_column_keyvalue_=leixing%3ddengyuzifuchuan

        public string insertkey(string key, string val)
        {
            string str = this[pagesearch].tostr();
            List<string> lst = new List<string>();
            foreach (string s in str.Split('&'))
            {
                if (string.IsNullOrEmpty(s)) continue;
                if (s.IndexOf(key + "=", StringComparison.OrdinalIgnoreCase) != -1) continue;
                lst.Add(s);
            }

            lst.Add(key + "=" + HttpContext.Current.Server.UrlEncode(val.ToString().Trim()));

            return string.Join("&", lst.ToArray());
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,去掉结尾字符串
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="strEnd">结尾字符串</param>
        /// <returns>返回去掉结尾后的字符串</returns>
        public string strend(string strSource, string strEnd)
        {
            return strSource.EndsWith(strEnd) ? strSource.Substring(0, strSource.Length - strEnd.Length) : strSource;
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,去掉起始字符串
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="strStart">起始字符串</param>
        /// <returns>返回去掉起始字符串后的字符串</returns>
        public string strstart(string strSource, string strStart)
        {
            return strSource.StartsWith(strStart) ? strSource.Substring(strStart.Length) : strSource;
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,分割字符串为字符串数组
        /// </summary>
        /// <param name="strSplit">分割字符串</param>
        /// <param name="strSource">分割的源字符串</param>
        /// <returns>分割后的字符串数组</returns>
        public string[] explode(string strSplit, string strSource)
        {
            return stringhelper.split(strSource, strSplit);
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,查找字符串是否在另外一个字符串里面 默认缺省的分隔符为逗号
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="strFind">被查找的字符串</param>
        /// <param name="chrSplit">用于分割的字符</param>
        /// <returns>true:存在</returns>
        public bool in_string(string strSource, string strFind, char chrSplit)
        {
            if (string.IsNullOrEmpty(strSource) || string.IsNullOrEmpty(strFind))
            {
                return false;
            }

            string[] strs = strSource.Split(chrSplit);
            foreach (string s in strs)
            {
                if (s.ToLower() == strFind.ToLower())
                    return true;
            }
            return false;
        }
        /// <summary>
        /// [此方法不再使用]兼容php方法,查找字符串是否在另外一个字符串里面 默认缺省的分隔符为逗号
        /// </summary>
        /// <param name="strSource">源字符串</param>
        /// <param name="strFind">被查找的字符串</param>
        /// <returns>true:存在</returns>
        public bool in_string(string strSource, string strFind)
        {
            return in_string(strSource, strFind, ',');
        }

        /// <summary>
        /// [此方法不再使用]兼容php方法,返回字符串数组的长度
        /// </summary>
        /// <param name="strs">字符串数组</param>
        /// <returns>返回数组的长度</returns>
        public int @sizeof(string[] strs)
        {
            return strs.Length;
        }

        /// <summary>
        /// 得到排序字段，先从前台取，如果取不到，就用传过来的值，采用降序 
        /// [2010-01-29 13:52 HanLei]<para />
        /// </summary>
        /// <param name="strColumn">排序字段</param>
        /// <returns></returns>
        public string orderbycolumn(string strColumn)
        {
            return orderbycolumn(strColumn, "desc");
        }

        /// <summary>
        /// 得到排序字段，先从前台取，如果取不到，就用传过来的值 
        /// [2010-01-28 14:12 HanLei]<para />
        /// </summary>
        /// <param name="strColumn">排序字段</param>
        /// <param name="strOrder">排序方式，asc，desc</param>
        /// <returns>返回排序字段</returns>
        public string orderbycolumn(string strColumn, string strOrder)
        {
            string strValue = getonevalue("cn");
            if (!string.IsNullOrEmpty(strValue))
            {
                strColumn = strValue.Trim();
            }

            strOrder = ordertype(strOrder);
            insertpagevalue("cn", strColumn);
            this["cn"] = strColumn;
            return " " + strColumn.Trim() + " " + strOrder;
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string getonevalue(string key)
        {
            string v = "";
            if (Request.HttpMethod == "POST")
            {
                //如果查询，直接定位到第一页。
                if (key.ToLower() == "page") return "0";
                v = Request.Form[key];
                if (v == null)
                {
                    v = Request.QueryString[key];
                }
            }
            else
            {
                v = Request.QueryString[key];
            }

            return v;
        }


        /// <summary>
        /// 获取排序方式，先从前台取，如果取不到，就用传过来的值
        /// [2010-01-28 14:21 HanLei]<para />
        /// </summary>
        /// <param name="strOrder">默认排序方式</param>
        /// <returns>返回排序方式</returns>
        public string ordertype(string strOrder = "")
        {
            string strValue = getonevalue("ot");
            if (!string.IsNullOrEmpty(strValue))
            {
                strOrder = strValue;
            }
            strOrder = strOrder.ToLower();
            
            strOrder = string.IsNullOrEmpty(strOrder) ? "desc" : strOrder; 
            
            insertpagevalue("ot", strOrder);
            this["ot"] = strOrder;
            return strOrder;
        }

        /// <summary>
        /// 功能:返回每页显示记录的数量
        /// [09.4.12 lxw]<para />
        /// </summary>
        public int pagesize
        {
            get
            {
                string strValue = getonevalue("ps");
                int intDefaultPageSize =

                    cookieshelper.getcookie("PageSize")
                    .toint32();

                if (intDefaultPageSize == 0)
                {
                    //默认为20条的了
                    intDefaultPageSize = 20;
                    cookieshelper.setcookie("PageSize", intDefaultPageSize.ToString());
                }

                if (!string.IsNullOrEmpty(strValue))
                {
                    if (intDefaultPageSize.ToString() != strValue)
                    {
                        intDefaultPageSize = strValue.toint32(20);
                        cookieshelper.setcookie("PageSize", strValue);
                    }
                }

                insertpagevalue("ps", intDefaultPageSize);
                return intDefaultPageSize;
            }
        }

        /// <summary>
        /// 得到当前页
        /// </summary>
        /// <returns>返回当前页的数字</returns>
        public int page
        {
            get
            {
                string strCurPage = getonevalue("page");
                if (strCurPage != null && strCurPage.Trim() != "")
                {
                    if (strCurPage.IndexOf(',')!=-1)
                    {
                        insertpagevalue("page", strCurPage.Split(',')[0]);
                        return strCurPage.Split(',')[0].toint32();
                    }
                    else
                    {
                        insertpagevalue("page", strCurPage);
                        return strCurPage.toint32();
                    }
                }
                else
                {
                    insertpagevalue("page", 0);
                    return 0;//返回第一页
                }
            }
        }

        /// <summary>
        /// 给模板里面输出键值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object this[string key]
        {
            set
            {
                //如果两次 可能会出现错误
                if (context.ContainsKey(key)) context.Remove(key);
                context.Put(key, value);
            }
            get
            {
                return context.Get(key);
            }
        }

        public void putkey(string key, object value)
        {
            if (context.ContainsKey(key)) context.Remove(key);
            context.Put(key, value);
        }

        public object getkey(string key)
        {
            return context.Get(key);
        }

        public string formatnumber(string d,int count=2)
        {
            double x = 0;
            double.TryParse(d, out x);

            return x.ToString("F"+count);
        }

        public string formatdate(string date,string fmt="yyyy-MM-dd")
        {
            try
            {
                var v = date.todatetime("", true);
                return v.ToString(fmt);
            }
            catch { }
            return "";
        }

        /// <summary>
        /// 动态解析htm
        /// </summary>
        /// <param name="templatFileName"></param>
        /// <returns></returns>
        public string formatview(string templatFileName)
        {
            //如果存在，才输出到外面
            if (velocity.TemplateExists(templatFileName))
            {
                //从文件中读取模板
                Template template = velocity.GetTemplate(templatFileName);

                //合并模板
                StringWriter writer = new StringWriter();
                template.Merge(context, writer);
                //输出
                return writer.ToString();
            }
            else
            {
                //如果不存在模板，也就不加载layout了。
                return "";
            }
        }

        //解析模板
        public string formatview(lxwdata has,string templatFileName)
        {
            //如果存在，才输出到外面
            if (velocity.TemplateExists(templatFileName))
            {
                //从文件中读取模板
                Template template = velocity.GetTemplate(templatFileName);

                IContext cnt = new VelocityContext();

                foreach (string key in has.Keys)
                {
                    string value = has[key].tostr();

                    if (cnt.ContainsKey(key)) cnt.Remove(key);
                    cnt.Put(key, value);
                }
                
               
                //合并模板
                StringWriter writer = new StringWriter();
                template.Merge(cnt, writer);
                //输出
                return writer.ToString();
            }
            else
            {
                //如果不存在模板，也就不加载layout了。
                return "";
            }
        }

        private void display(string templatFileName)
        {
            if (_cancelview) return;
            string bodyhtml = "";
            //如果存在，才输出到外面
            if (velocity.TemplateExists(templatFileName))
            {
                //从文件中读取模板
                Template template = velocity.GetTemplate(templatFileName);
                //合并模板
                StringWriter writer = new StringWriter();
                template.Merge(context, writer);
                //输出
                bodyhtml = writer.ToString();
            }
            else
            {
                //如果不存在模板，也就不加载layout了。
                return;
            }

            string layouthtml = "$bodycontent";
            if (layoutname != "")
            {
                string viewpath = "/layout/" + layoutname + ".htm";
                if (velocity.TemplateExists(viewpath))
                {
                    //从文件中读取模板
                    Template template = velocity.GetTemplate(viewpath);

                    //合并模板
                    StringWriter writer = new StringWriter();
                    template.Merge(context, writer);
                    //输出
                    layouthtml = writer.ToString();
                }
            }

            //如果前面有输出，不能把前面的clear掉。
            //Response.Clear();
            Response.Write(
                jqueryfmt(layouthtml.Replace("$bodycontent", bodyhtml))
                );
            //Response.Flush();
        }

        /// <summary>
        /// 处理$. $(的东西，这是jquery的写法
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        string jqueryfmt(string p)
        {
            return p;
            //防止前面计息不了jquery的东西,这里很变态，主要是处理前面模板中可能存在的错误信息
            //return p.Replace("." + NVelocity.App.Velocity.jquery_token, "$.").Replace(NVelocity.App.Velocity.jquery_token, "");
        }
        /// <summary>
        /// 查询关键字
        /// </summary>
        const string _sw_ = "_sw_";
        /// <summary>
        /// 需要保存状态的key
        /// </summary>
        const string _sk_ = "_sk_";
        /// <summary>
        /// 组合查询语句
        /// </summary>
        /// <returns></returns>
        public string search(string where = "")
        {

            string searchkeys = paramsvalue("_lxw_column_searchkeys_", true);
            string exp = paramsvalue("_lxw_column_keyvalue_", true).Replace("&gt;",">");

            //移除这些不要的键
            //removekey("_lxw_column_searchkeys_", "_lxw_column_keyvalue_");

            ////如果不是post的时候，直接获取where数据
            ////这部分有点凑数的感觉，目前没有好的想法
            //if (Request.ServerVariables["REQUEST_METHOD"].ToUpper() == "GET")
            //{
            //    //还原where语句
            //    if (v_s(_sw_).Length > 0)
            //        where = cryptohelper.decode(v_s(_sw_));

            //    //还原查找语句，其实基本上用不到，只是用于保存状态而已
            //    string keys = v_s(_sk_);
            //    if (keys.Length > 0)
            //    {
            //        this.insertpagevalue(_sk_, keys);
            //        foreach (var k in keys.Split(','))
            //            this.insertpagevalue(k, v_s(k));
            //    }                
            //}
            //else
            {
                //这部分是查询语句，必须通过post方式提交过来的。
                //string keys = "";
                foreach (string s in searchkeys.Split(','))
                {
                    if (string.IsNullOrEmpty(s)) continue;
                    express expr = (express)Enum.Parse(typeof(express), requesthelper.fromurlparamsgetvaluebykey(exp, s,">" ));
                    //switch (expr)
                    //{
                    //    case express.dengyuriqi:
                    //    case express.budengyuriqi:
                    //    case express.dayuriqi:
                    //    case express.xiaoyuriqi:
                    //    case express.dayudengyuriqi:
                    //    case express.xiaoyudengyuriqi:
                    //        dbdatehelper.querydatetime(ref where,s,para
                    //}
                    //这里必须获取的是form的值
                    string strs = HttpUtility.UrlDecode(Request.QueryString[s].tostr(), Encoding.GetEncoding("gbk"));
                    string str = paramsvalue(s, true);
                    
                    //插入到查询条件中
                    //this.insertpagevalue(s, str);
                    //保持状态，前台能使用
                    //this[s] = str;

                    //keys += "," + s;
                    dbdatehelper.querystring(ref where, s, str, orand.and, expr);
                }

                //把查询关键字放入条件中
                //if (keys.Length > 0)
                //    this.insertpagevalue(_sk_, keys.Substring(1));
            }

            //把组合好的where语句加密放入查询条件中
            //if (where.Length > 0)
            //    this.insertpagevalue(_sw_, cryptohelper.encode(where));

            return where;
        }


        /// <summary>
        /// 输出信息
        /// </summary>
        /// <param name="p"></param>
        public void write(string p,params object[] arg)
        {
            if (arg != null && arg.Length > 0)
                p = string.Format(p, arg);

            Response.StatusCode = 200;
            Response.Write(p);
            //如果输出 就不要显示模板
            this.cancelview();
        }

        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="p"></param>
        public void alert(string p)
        {
            Response.Write("alert(\'"+p.Replace("'","\"")+"\');");
            //如果输出 就不要显示模板
            this.cancelview();
        }
        public void alert_exe(string alert = "", string exe = "")
        {
            res re = new res();
            re.alert = alert;
            re.exe = exe;
            string json = JSON.stringify(re);
            Response.Write(json);
            //如果输出 就不要显示模板
            this.cancelview();
        }

        public void exe_json(string exe)
        {
            res re = new res();
            re.exe = exe;
            string json = JSON.stringify(re);
            Response.Write(json);
            //如果输出 就不要显示模板
            this.cancelview();

        }
        public void alert_json(string alert)
        {
            res re = new res();
            re.alert = alert;
            string json = JSON.stringify(re);
            Response.Write(json);
            //如果输出 就不要显示模板
            this.cancelview();
        }

        /// <summary>
        /// 提示信息，并转向，注意，只是针对前面form.submit提交才有用
        /// </summary>
        /// <param name="url"></param>
        /// <param name="msg"></param>
        public void topage(string url, string msg = "")
        {
            string text = string.IsNullOrEmpty(msg) ? "" : "alert('" + msg.Replace("'", "\'") + "');";
            text += "location.href='" + url + "';";
            Response.Write(text);
        }

        /// <summary>
        /// 得到字典集合
        /// </summary>
        /// <param name="bianma"></param>
        /// <param name="paixu"></param>
        /// <returns></returns>
        public DataRowCollection getzidianrows(string bianma, string paixu = "")
        {
            string sql = "select * from zidian where zidianleibieid in(select zidianleibieid from zidianleibie where bianma='" + bianma + "') " + paixu;
            return queryhelper.rows(sql);
        }

        /// <summary>
        /// 通过表得到信息
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="paixu"></param>
        /// <returns></returns>
        public DataRowCollection gettablerows(string tablename, string paixu = "")
        {
            string sql = "select * from " + tablename + " " + paixu;
            return queryhelper.rows(sql);
        }

        /// <summary>
        /// 重定向到对应的页面,所有提交的信息都已经保留。
        /// </summary>
        /// <param name="url"></param>
        public void redirect(string url)
        {
            Response.Redirect(url);
        }

        /// <summary>
        /// 输出信息
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="p"></param>
        public void writetable(string sql, char p)
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in sqlhelper.rows(sql))
            {
                object[] objs = dr.ItemArray;
                sb.Append(p.tostr());
                sb.Append(string.Join(p.tostr(), objs));
            }

            string ret = sb.tostr();
            if (ret.Length > 0) ret = ret.Substring(1);

            write(ret);
        }

        /// <summary>
        /// 设置table和id
        /// </summary>
        /// <param name="p"></param>
        /// <param name="zj">主键</param>
        public void settable(string p,string zj = "")
        {
            table = p;
            if (string.IsNullOrEmpty(zj))
            {
                string sql = "SELECT IDENTITYCOL  FROM  "+p+" where 1<>1";
                try
                {
                    zj = sqlhelper.dataset(sql).Tables[0].Columns[0].ColumnName;
                }
                catch {
                    throw new Exception(p+"没有设置自动递增列！");
                }
            }
            pk = zj;

            //把主键输出到界面中
            this["pk"] = pk;
        }

        public bool Post { get {
            return Request.HttpMethod == "POST";
        } }

        /// <summary>
        /// 输出json对象
        /// </summary>
        /// <param name="p"></param>
        public void json(string p)
        {
            //把相关的文字替换掉
            write(p.Replace("易企秀", "云图").Replace("秀点", "云点").Replace("eqxiu.com", "yunto.cc"));
            //不要出现秀点
            Response.ContentType = "application/json";
            //Content-Type: application/json; charset=utf-8
        }
    }

    public class ExitException : Exception
    {
        public ExitException() : base() { }
    }

    public class res
    {
        public string alert { get; set; }
        public string exe { get; set; }
    }
}
